package com.naiterui.ehp.bs.b2c.order.service.impl.logistics;


import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bp.utils.net.RestHttpUtil;
import com.naiterui.ehp.bs.b2c.common.remote.B2cRemoterConfig;
import com.naiterui.ehp.bs.b2c.order.bo.LogisticsInfoBO;
import com.naiterui.ehp.bs.b2c.order.bo.LogisticsTraceLogBO;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.BaseResponse;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.request.RecipteInfo;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.request.SfTraceQueryRequest;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.response.Route;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.response.RouteResponse;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.response.SfTraceLogs;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.sf.response.SfTraceQueryResponse;
import com.naiterui.ehp.bs.b2c.thirdparty.service.IPrescriptionPlatformService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Slf4j
@Service("shunfeng")
public class SfLogisticsTracesServiceImpl extends AbstractLogisticsTraceService<SfTraceQueryRequest> {

    @Autowired
    private IPrescriptionPlatformService prescriptionPlatformService;
    @Autowired
    private B2cRemoterConfig b2cRemoterConfig;

    @Override
    public Map<String, LogisticsInfoBO> getTrace(List<String> deliveryIds) {
        Map<String, LogisticsInfoBO> result = new HashMap<>();
        try {
            SfTraceQueryRequest request = new SfTraceQueryRequest();
            List<RecipteInfo> param = deliveryIds.stream()
                .map(e -> RecipteInfo.builder().recipteId(e).sourceId(ConfigUtil.getString("prescription.platform.sourceId")).build())
                .collect(Collectors.toList());
            // request.setParam(param);
            request.setRecipeIds(deliveryIds);
            SfTraceQueryResponse traceQueryResponse = this.execute(request, new ParameterizedTypeReference<SfTraceQueryResponse>() {
            });
            List<SfTraceLogs> data = traceQueryResponse.getData();
            if (CollectionUtils.isNotEmpty(data)) {
                data.forEach(e -> {
                    // 循环一个处方单
                    LogisticsInfoBO logisticsInfo = new LogisticsInfoBO();
                    List<LogisticsTraceLogBO> traceLogs = new ArrayList<>();
                    String recipteId = e.getRecipeId();
                    // 当前处方单的物流信息（获取的是顺丰的xml格式的信息，需要自行转换）
                    // StringReader xmlReader = new StringReader(e.getData());
                    // 物流信息
                    //Response responseInfo = JAXB.unmarshal(xmlReader, Response.class);
                    if (StringUtils.isNotEmpty(e.getTrace())) {
                        RouteResponse response = JsonMapper.toObject(e.getTrace(), RouteResponse.class);
                        if (CollectionUtils.isNotEmpty(response.getRoutes())) {
                            List<Route> route = response.getRoutes();
                            traceLogs = route.stream().map(r -> LogisticsTraceLogBO.builder().address(r.getAcceptAddress())
                                .time(DateUtil.parseStrToCustomPatternDate(r.getAcceptTime(), DateUtil.DATE_TIME_FORMAT)).content(r.getRemark())
                                .build()).collect(Collectors.toList());
                            logisticsInfo.setTraceLogs(traceLogs);
                            logisticsInfo.setDeliveryId(e.getRecipeId());
                            List<String> opCodes = route.stream().map(r -> r.getOpcode()).collect(Collectors.toList());
                            if (opCodes.contains("648")) {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_REJECT);
                            } else if (opCodes.contains("80") || opCodes.contains("8000") || opCodes.contains("607")) {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_RECEIVED);
                            } else if (opCodes.contains("30") || opCodes.contains("31") || opCodes.contains("3036") || opCodes.contains("44") ||
                                opCodes.contains("70") || opCodes.contains("130") || opCodes.contains("123") || opCodes.contains("99")) {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_ONWAY);
                            } else if (opCodes.contains("50")) {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_PICKUP);
                            } else if (opCodes.contains("33")) {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_NONE);
                            } else {
                                logisticsInfo.setStatus(LogisticsInfoBO.STATUS_NONE);
                            }
                        } else {
                            logisticsInfo.setStatus(LogisticsInfoBO.STATUS_NONE);
                        }
                    } else {
                        logisticsInfo.setStatus(LogisticsInfoBO.STATUS_NONE);
                    }
                    result.put(e.getRecipeId(), logisticsInfo);
                });
            }

        } catch (Exception e) {
            log.error("获取处方流转平台顺丰物流信息失败，e", e);
        }
        return result;
    }

    @Override
    protected <E extends BaseResponse> E execute(SfTraceQueryRequest sfTraceQueryRequest, ParameterizedTypeReference<E> responseTypeReference)
        throws IOException {
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", prescriptionPlatformService.getAccessToken());
        header.put("Content-Type", "application/json");

        ResponseEntity<SfTraceQueryResponse> responseEntity = RestHttpUtil.post()
            .header(header)
            .body(JsonMapper.toJson(sfTraceQueryRequest))
            .url(b2cRemoterConfig.getPlatformRouteInfoUrl())
            .execute(new ParameterizedTypeReference<SfTraceQueryResponse>() {
            });

        return (E) responseEntity.getBody();

    }
}
